import { getLocalHistories } from '@/utils/storage'

export type Article = {
  title: string
  aut_id: number
  pubdate: string
  ch_id: number
  cover: {
    type: 1 | 3 | 0
    images: never[]
  }
  is_top: number
  art_id: string
  aut_name: string
  comm_count: number
  like_count: number
  collect_count: number
}

const initState = {
  suggestion: [] as string[],
  histories: getLocalHistories(),
  results: [] as Article[],
}

export type SeatchAction =
  | { type: 'seatch/saveSuggestion'; payload: string[] }
  | { type: 'seatch/clearSuggestion' }
  | { type: 'seatch/saveHistory'; payload: string[] }
  | { type: 'seatch/clearHistory' }
  | { type: 'seatch/saveResult'; payload: Article[] }

export const searchReducer = (state = initState, actions: SeatchAction) => {
  switch (actions.type) {
    case 'seatch/saveSuggestion':
      return { ...state, suggestion: actions.payload }
    case 'seatch/clearSuggestion':
      return { ...state, suggestion: [] }
    case 'seatch/saveHistory':
      return { ...state, histories: actions.payload }
    case 'seatch/clearHistory':
      return { ...state, histories: [] }
    case 'seatch/saveResult':
      return { ...state, results: actions.payload }
    default:
      return state
  }
}
